﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.IO;
using System.Data.OleDb;

using INSAForManagers.Models;

namespace INSAForManagers
{
    public partial class FormMain : Form
    {
        
        private static ToolStripMenuItem mnuSMAdd;
        private static ToolStripMenuItem mnuSConfig;
        private static ToolStripMenuItem mnuSSum;
        private static ToolStripMenuItem mnuSSumOfElement;
        private static ToolStripMenuItem mnuSManagerInfo;

        public static ToolStripMenuItem MnuSManagerInfo
        {
            get { return FormMain.mnuSManagerInfo; }
            set { FormMain.mnuSManagerInfo = value; }
        }
        private static ToolStripMenuItem mnuSACard;
        private static ToolStripMenuItem mnuSEvalue;
        private static ToolStripMenuItem mnuSWorkMultiSum;
        
        public static ToolStripMenuItem mnuStaticMMain;
        public static ToolStripMenuItem mnuStaticEMain;
        public static ToolStripMenuItem mnuStaticAMain;

        //DataTable For 정보
        private DataTable tblInfo = new DataTable();
        
        public FormMain()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
                       
                         
            //메인 폼 환경변수에 등록
            Config.MainForm = this;

            //프로그램 시작 경로 환경변수에 등록
            Config.Path = Application.StartupPath;

            //데이터베이스 연결
            DBUtil.oleConnect();
           


            //다면평가대상자 전체 수
            Config.NumOfTagets = DBUtil.getMTargetCount( );


            Config.EnabledListViewEvent = true;

            //메뉴를 전역변수와 연결
            setStaticMenu();

            //버전 정보를 환경변수에 등록
            Config.Version = DBUtil.getVersion(1);

            //DataGridView 초기화
            initDgvInfo();
        }

        private void setStaticMenu()
        {            
            mnuSConfig          = mnuConfig;
            mnuStaticMMain      = mnuMMain;
            mnuStaticEMain      = mnuEMain;
            mnuStaticAMain      = mnuAMain;
            mnuSSumOfElement    = mnuSumOfElement;
            mnuSManagerInfo     = mnuManagerInfo;
            mnuSACard           = mnuACard;
            mnuSSum             = mnuSum;
            mnuSEvalue          = mnuEvalue;
            mnuSWorkMultiSum    = mnuWorkMultiSum;
            
            mnuSMAdd = mnuMAdd;
        }

        public static  void setMenuDisabled()
        {
         
          
            mnuStaticMMain.Enabled = false;
            mnuStaticEMain.Enabled = false;
            mnuStaticAMain.Enabled = false;
        }

        public static void setMenuEnabled()
        {
         
            
            mnuStaticMMain.Enabled = true;
            mnuStaticEMain.Enabled = true;
            mnuStaticAMain.Enabled = true;
        }

        public static void setMnuMAddEnabled() {
            mnuSMAdd.Enabled = true;
        }

        public static void setMnuConfigEnabled()
        {
            mnuSConfig.Enabled = true;
        }

        public static void setMnuSumOfElementEnabled()
        {
            mnuSSumOfElement.Enabled = true;
        }

        public static void setMnuSumEnabled()
        {
            mnuSSum.Enabled = true;
        }

        public static void setMnuSACardEnabled()
        {
            mnuSACard.Enabled = true;
        }

        public static void setMnuSManagerInfoEnabled()
        {
            mnuSManagerInfo.Enabled = true;
        }

        public static void setMnuSEvalueEnabled()
        {
            mnuSEvalue.Enabled = true;
        }

        public static void setMnuSWorkMultiSumEnabled()
        {
            mnuSWorkMultiSum.Enabled = true;
        }

        public static void setManagerInfoEnabled()
        {
            mnuSManagerInfo.Enabled = true;
        }


        /*********************************
         * 이벤트 모음
         ********************************/

        
        private void mnuMAdd_Click(object sender, EventArgs e)
        {
            //다면평가자 입력 폼 생성            
            FormMAdd f = new FormMAdd(this);
            f.MdiParent = this;
            f.Show();

            mnuMAdd.Enabled = false;
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {   
            //응용프로그램 종료
            Application.Exit();
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //MDB 연결 종료            
            DBUtil.oleClose();
        }

        private void mnuManagerInfo_Click(object sender, EventArgs e)
        {
            //사용자정보입력 폼 실행
            Form f = new FormManagerInfo(this);
            f.MdiParent = this;
            f.Show();

            mnuManagerInfo.Enabled = false;
        }

        private void mnuMTargetOpen_Click(object sender, EventArgs e)
        {
            //다면평가수합 폼 실행
            FormMultiGather f = new FormMultiGather(this);
            f.MdiParent = this;
            f.Show();
        }

        private void mnuSumOfElement_Click(object sender, EventArgs e)
        {
            //요소별 집계 폼 실행
            FormElemnets f = new FormElemnets(this);
            f.MdiParent = this;
            f.Show();

            mnuSumOfElement.Enabled = false;
        }

        private void mnuConfig_Click(object sender, EventArgs e)
        {
            //환경설정 폼 실행
            Form f = new FormConfig(this);
            f.MdiParent = this;
            f.Show();

            mnuConfig.Enabled = false;
        }

        private void mnuSum_Click(object sender, EventArgs e)
        {
            //다면평가 합계 폼 실행
            Form f = new FormSUM(this);
            f.MdiParent = this;
            f.Show();

            mnuSum.Enabled = false;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            
            try
            {
                

               

                //등록된 사용자가 있으면 로그인 처리함
                if (DBUtil.isRegistedUserInfo() == true)
                {

                    FormLogin f = new FormLogin();
                    if (f.ShowDialog() == DialogResult.Cancel)
                    {
                        Config.State = Config.STATE_EXIT;
                    }
                }
                else
                {
                    Config.State = Config.STATE_INIT;
                }

                /*
                 * 로그인 취소한 경우
                 * */
                if (Config.State == Config.STATE_EXIT)
                {
                    this.Close();
                }


                /*
                 * 프로그램 상태가 초기 상태이면 사용자정보등록 폼을 실행시키고
                 * 초기 상태임에도 불구하고 정보를 입력하지 않고 취소하면 메인 폼을 닫고 로그인 폼을 종료시킨다.
                 * */
                if (Config.State == Config.STATE_INIT)
                {

                    if (MessageBox.Show("프로그램을 처음으로 실행시키셨습니다.\n\n사용자정보를 입력해야지만 프로그램을 정상적으로 사용하실 수 있습니다.\n\n지금 사용자정보를 입력하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {

                        //사용자정보 입력 폼 실행
                        mnuManagerInfo.PerformClick();
                        mnuManagerInfo.Enabled = false;
                    }
                    else
                    {
                        //메인 폼 닫기
                        this.Close();

                    }
                }

                /*************
                 * 사용자정보등록여부 확인하여
                 * 없으면 초기 상태로 설정하고 -> 사용자등록정보 폼 실행하기 위해
                 * 있으면 각종 초기값들을 설정한다.
                 *************/
                if (Config.State == Config.STATE_OK)
                {
                    //Config.UserType 값은 로그인 할 때 할당됨
                    Config.setMvi();


                    //다면평가자 목록
                    Config.ValuerList = DBUtil.getValuerList();

                    //메인 정보
                    try
                    {
                        stateRefresh();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.Close();
                    }


                }

                // 다면평가유형 초기화
                tscTargetType.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            

        }

        /*
         * @요약: 메인 정보 DataGridView에 정보를 뿌려준다.
         * */
        public void stateRefresh()
        {
            try
            {
                //확인자 정보
                dgvInfo.Rows[0].Cells[1].Value = Config.Mvi.Confirmer;

                //평정자 정보
                dgvInfo.Rows[1].Cells[1].Value = Config.Mvi.Evaluer1 + ((Config.Mvi.Evaluer2.Length > 1) ? (" / " + Config.Mvi.Evaluer2) : "");

                //설명
                dgvInfo.Rows[2].Cells[1].Value = "등록|다면|근평";

                //대상자 전체 인원
                dgvInfo.Rows[3].Cells[1].Value = DBUtil.getMTargetCount() + " | " + DBUtil.getMutiCount() + " | " + DBUtil.getEvalueCount();

                //일반
                dgvInfo.Rows[4].Cells[1].Value = DBUtil.getMTargetCount(TargetType.GENERAL) + " | " + DBUtil.getMutiCount(TargetType.GENERAL) + " | " + DBUtil.getEvalueCount(TargetType.GENERAL);

                //보건
                dgvInfo.Rows[5].Cells[1].Value = DBUtil.getMTargetCount(TargetType.NURSE) + " | " + DBUtil.getMutiCount(TargetType.NURSE) + " | " + DBUtil.getEvalueCount(TargetType.NURSE);

                //전문상담
                dgvInfo.Rows[6].Cells[1].Value = DBUtil.getMTargetCount(TargetType.COUNSELLING) + " | " + DBUtil.getMutiCount(TargetType.COUNSELLING) + " | " + DBUtil.getEvalueCount(TargetType.COUNSELLING);

                //사서
                dgvInfo.Rows[7].Cells[1].Value = DBUtil.getMTargetCount(TargetType.LIBRARIAN) + " | " + DBUtil.getMutiCount(TargetType.LIBRARIAN) + " | " + DBUtil.getEvalueCount(TargetType.LIBRARIAN);

                //영양
                dgvInfo.Rows[8].Cells[1].Value = DBUtil.getMTargetCount(TargetType.FOODSERVICE) + " | " + DBUtil.getMutiCount(TargetType.FOODSERVICE) + " | " + DBUtil.getEvalueCount(TargetType.FOODSERVICE);

                //기간제
                dgvInfo.Rows[9].Cells[1].Value = DBUtil.getMTargetCount(TargetType.FIXEDTERM) + " | " + DBUtil.getMutiCount(TargetType.FIXEDTERM) + " | " + DBUtil.getEvalueCount(TargetType.FIXEDTERM);


                //다면평가자목록
                Config.ValuerList = DBUtil.getValuerList();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n원인: 사용자 정보 누락 등", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }

        private void mnuProgramInfo_Click(object sender, EventArgs e)
        {
            Form f = new FormProgramInfo();            
            f.ShowDialog();
        }

        private void mnuEvalue_Click(object sender, EventArgs e)
        {
            Form f = new FormEEvalue(this);
            f.MdiParent = this;
            f.Show();

            mnuEvalue.Enabled = false;
        }

        private void mnuWorkMultiSum_Click(object sender, EventArgs e)
        {
            Form f = new FormWorkMultiSum(this);
            f.MdiParent = this;
            f.Show();

            mnuWorkMultiSum.Enabled = false;
        }

        private void lnkInfoViewOrHide_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (pInfo.Visible == true)
            {
                pInfo.Visible = false;
                lnkInfoViewOrHide.Text = "정보 보이기";
            }
            else
            {
                pInfo.Visible = true;
                lnkInfoViewOrHide.Text = "정보 감추기";
            }
        }

        private void mnuMultiExport_Click(object sender, EventArgs e)
        {
            if (DBUtil.isExistTMultiInfo() == true)
            {
                Thread t = new Thread(new ThreadStart(exportFile));
                t.Start();
            }
            else
            {
                MessageBox.Show("다면평가정보가 없습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void exportFile()
        {
            try
            {
                mnuMultiExport.Enabled = false;

                progressBar.Visible = true;
                lblStateMsg.Text = "파일 작성 중...";


                //엑셀 열기
                Util.openXls(Application.StartupPath + "\\MultiSum");
                progressBar.Value = 5;

                //레인지 객체 선언
                Excel.Range range;

                // 평가기간 설정

                //시작
                range = Util.OSheet.get_Range("A3", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.SDate);

                //종료
                range = Util.OSheet.get_Range("A4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.EDate);

                //평정자 성명
                range = Util.OSheet.get_Range("I4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Evaluer1 + (Config.Mvi.Evaluer2.Equals("") ? "" : "," + Config.Mvi.Evaluer2));

                //확인자 성명
                range = Util.OSheet.get_Range("E4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Confirmer);

                //소속
                string organ_name = DBUtil.getOrganName(Config.Mvi.Organ);

                //평가자
                string valuer = "다면평가자";

                progressBar.Value = 10;

                lblStateMsg.Text = "파일에 데이터 입력 중...";
                //레코드
                ArrayList list = DBUtil.getMTargetListFromTMULTITABLE(getTargetType());
                object[,] arr = new object[list.Count, 10];
                for (int i = 0; i < list.Count; i++)
                {
                    //소속
                    arr[i, 0] = organ_name;
                    arr[i, 1] = DBUtil.getMTargetName(list[i].ToString());
                    arr[i, 2] = valuer;
                    arr[i, 3] = DBUtil.getElementInfo(list[i].ToString(), "1")[1];
                    arr[i, 4] = DBUtil.getElementInfo(list[i].ToString(), "2")[1];
                    arr[i, 5] = DBUtil.getElementInfo(list[i].ToString(), "3")[1];
                    arr[i, 6] = DBUtil.getElementInfo(list[i].ToString(), "4")[1];
                    arr[i, 7] = DBUtil.getElementInfo(list[i].ToString(), "5")[1];
                    arr[i, 8] = DBUtil.getItemFromTMultitable(list[i].ToString(), "1");
                    arr[i, 9] = DBUtil.getItemFromTMultitable(list[i].ToString(), "2");
                    if (progressBar.Value < 90) progressBar.Value += 1;
                }

                lblStateMsg.Text = "파일에 서식 적용 중...";

                range = Util.OSheet.get_Range("A16", "J" + (15 + list.Count).ToString());
                range.set_Value(Missing.Value, arr);

                range = Util.OSheet.get_Range("A16", "k" + (15 + list.Count).ToString());
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

                range = Util.OSheet.get_Range("A" + (16 + list.Count).ToString(), "k1000");
                range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                lblStateMsg.Text = "파일 내보내는 중...";
                string fileName = path + "\\교사다면평가표(" + DBUtil.getOrganName(Config.Mvi.Organ) + ")_" + (string)tscTargetType.Items[tscTargetType.SelectedIndex] + ".xls";
                Util.OWorkBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                progressBar.Value = 90;

                Util.closeXls();


                progressBar.Value = 100;
                progressBar.Visible = false;
                lblStateMsg.Text = "완료!";

                MessageBox.Show(fileName + "  \n\n위 파일을 내문서에 내보냈습니다.  ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Thread.Sleep(500);

                lblStateMsg.Text = "";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Util.closeXls();
            }
            finally
            {
                mnuMultiExport.Enabled = true;
            }
        }

        private void mnuEvalueExport_Click(object sender, EventArgs e)
        {
            if (DBUtil.isExistWorkEvalueInfo(getTargetType(), "0") == true && DBUtil.isExistWorkEvalueInfo(getTargetType(), "1") == true)
            {
                Thread t = new Thread(new ThreadStart(exportEvalueFile));
                t.Start();
            }
            else
            {
                MessageBox.Show("내보내기할 데이터가 없습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void exportEvalueFile()
        {
            try
            {
                progressBar.Visible = true;
                lblStateMsg.Text = "근무성적평정 파일 작성 중...";

                /*************************************************
                 * 다면평가표
                 *************************************************/
                Util.openXls(Application.StartupPath + "\\WorkEvalue");
                progressBar.Value = 5;

                //평정기간설정
                Excel.Range range = Util.OSheet.get_Range("A3", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.SDate);

                range = Util.OSheet.get_Range("A4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.EDate);

                //확인자
                range = Util.OSheet.get_Range("E3", Missing.Value);
                range.set_Value(Missing.Value, "교장");

                range = Util.OSheet.get_Range("E4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Confirmer);

                //평정자
                range = Util.OSheet.get_Range("I3", Missing.Value);
                range.set_Value(Missing.Value, "교감");

                range = Util.OSheet.get_Range("I4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Evaluer1 + "," + Config.Mvi.Evaluer2);

                lblStateMsg.Text = "근무성적평정 데이터 입력 중...";
                progressBar.Value = 10;

                //근무성적평정대상자 목록
                ArrayList list = DBUtil.getMTargetArrayFromWorkControlTable(getTargetType());

                int rowIndex = 16;//2행씩 증가
                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tmp = (ArrayList)list[i];

                    double total = 0;

                    //소속
                    range = Util.OSheet.get_Range("A" + (rowIndex).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, DBUtil.getOrganName(Config.Mvi.Organ));

                    //성명
                    range = Util.OSheet.get_Range("B" + (rowIndex).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, DBUtil.getMTargetName(tmp[1].ToString()));

                    //평정자
                    range = Util.OSheet.get_Range("C" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "평정자");

                    //근무성적평정정보(평정자)
                    ArrayList evaluePoint = DBUtil.getWorkEvalueInfo("0", tmp[1].ToString());
                    if (evaluePoint.Count == 0)
                    {
                        MessageBox.Show("평정자 및 확인자 모두 평정 하신 후 내보내기를 하십시오.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        Util.closeXls();
                        return;
                    }
                    //교육자로서의 품성
                    range = Util.OSheet.get_Range("D" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[0]);

                    //공직자로서의 자세
                    range = Util.OSheet.get_Range("E" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[1]);

                    //학습지도
                    range = Util.OSheet.get_Range("F" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[2]);

                    //생활지도
                    range = Util.OSheet.get_Range("G" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[3]);

                    //교육연구 및 담당업무
                    range = Util.OSheet.get_Range("H" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[4]);

                    //평정점
                    range = Util.OSheet.get_Range("I" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[5]);

                    //환산점
                    range = Util.OSheet.get_Range("J" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[6]);

                    //총점에 합산
                    total += Double.Parse(evaluePoint[6].ToString());

                    //확인자
                    range = Util.OSheet.get_Range("C" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "확인자");

                    //근무성적평정정보(확인자)
                    evaluePoint = DBUtil.getWorkEvalueInfo("1", tmp[1].ToString());
                    if (evaluePoint.Count == 0)
                    {
                        MessageBox.Show("평정자 및 확인자 모두 평정 하신 후 내보내기를 하십시오.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        Util.closeXls();
                        return;
                    }
                    //교육자로서의 품성
                    range = Util.OSheet.get_Range("D" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[0]);

                    //공직자로서의 자세
                    range = Util.OSheet.get_Range("E" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[1]);

                    //학습지도
                    range = Util.OSheet.get_Range("F" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[2]);

                    //생활지도
                    range = Util.OSheet.get_Range("G" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[3]);

                    //교육연구 및 담당업무
                    range = Util.OSheet.get_Range("H" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[4]);

                    //평정점
                    range = Util.OSheet.get_Range("I" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[5]);

                    //환산점
                    range = Util.OSheet.get_Range("J" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, evaluePoint[6]);

                    //총점에 합산
                    total += Double.Parse(evaluePoint[6].ToString());

                    //총점
                    range = Util.OSheet.get_Range("K" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, total.ToString("#0.000"));

                    rowIndex += 2;

                }
                
                lblStateMsg.Text = "서식 적용 중...";
                progressBar.Value = 30;

                range = Util.OSheet.get_Range("A16", "K" + (rowIndex - 1).ToString());
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

                progressBar.Value = 50;

                range = Util.OSheet.get_Range("A" + rowIndex.ToString(), "K" + Util.lastRow() + 1);
                range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

                progressBar.Value = 70;

                lblStateMsg.Text = "엑셀 파일 내보내는 중...";
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string fileName = path + "\\근무성적평정(" + DBUtil.getOrganName(Config.Mvi.Organ) + ")_" + tscTargetType.Items[tscTargetType.SelectedIndex] + ".xls";

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                Util.OWorkBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, false, false, Missing.Value, Missing.Value, Missing.Value);
                 
                lblStateMsg.Text = "";
                progressBar.Value = 100;

                Util.closeXls();
                Thread.Sleep(1000);

                lblStateMsg.Text = "다면평가 및 근무성적평정 합산 파일 작성 중...";
                progressBar.Value = 0;
                /*******************************************
                 * 다면평가 및 근무성적 합산표 파일 내보내기
                 *******************************************/
                Util.openXls(Application.StartupPath + "\\WorkEvalueSum");

                progressBar.Value = 10;

                //평정기간설정
                range = Util.OSheet.get_Range("A3", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.SDate);

                range = Util.OSheet.get_Range("A4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.EDate);

                //확인자
                range = Util.OSheet.get_Range("K3", Missing.Value);
                range.set_Value(Missing.Value, "교장");

                range = Util.OSheet.get_Range("K4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Confirmer);

                //평정자
                range = Util.OSheet.get_Range("N3", Missing.Value);
                range.set_Value(Missing.Value, "교감");

                range = Util.OSheet.get_Range("N4", Missing.Value);
                range.set_Value(Missing.Value, Config.Mvi.Evaluer1 + "," + Config.Mvi.Evaluer2);

                progressBar.Value = 20;

                //다면평가합산 테이블에서 순위 오름 차순으로 pcode호출
                rowIndex = 13;

                lblStateMsg.Text = "데이터 입력 중....기다려주십시오.";
                ArrayList ratio = DBUtil.getRatioNum(getTargetType());
                int su = Int32.Parse(ratio[0].ToString());
                int wo = Int32.Parse(ratio[1].ToString());
                int mi = Int32.Parse(ratio[2].ToString());
                int ya = Int32.Parse(ratio[3].ToString());

                list = DBUtil.getMTargetFromWorkEvalueSum(getTargetType());

                for (int i = 0; i < list.Count; i++)
                {
                    //소속
                    range = Util.OSheet.get_Range("A" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, DBUtil.getOrganName(Config.Mvi.Organ));

                    //성명
                    range = Util.OSheet.get_Range("B" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, DBUtil.getMTargetName(list[i].ToString()));

                    //근무성적평정
                    range = Util.OSheet.get_Range("D" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "근무성적\n평정");

                    //평정자
                    range = Util.OSheet.get_Range("E" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "평정자");

                    //확인자
                    range = Util.OSheet.get_Range("E" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "확인자");

                    //다면평가
                    range = Util.OSheet.get_Range("D" + (rowIndex + 2).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, "다면평가");

                    //합산표 정보
                    ArrayList suminfo = DBUtil.getWorkMultiSumInfo(list[i].ToString());


                    //평정자
                    range = Util.OSheet.get_Range("F" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, Double.Parse(suminfo[2].ToString()).ToString("##.000"));

                    //확인자
                    range = Util.OSheet.get_Range("F" + (rowIndex + 1).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, Double.Parse(suminfo[3].ToString()).ToString("##.000"));

                    //다면평가
                    range = Util.OSheet.get_Range("F" + (rowIndex + 2).ToString(), Missing.Value);
                    range.set_Value(Missing.Value, Double.Parse(suminfo[4].ToString()).ToString("##.000"));

                    //총점
                    range = Util.OSheet.get_Range("G" + rowIndex.ToString(), Missing.Value);
                    range.set_Value(Missing.Value, Double.Parse(suminfo[5].ToString()).ToString("##.000"));

                    range = Util.OSheet.get_Range("J" + rowIndex.ToString(), Missing.Value);
                    string strTmp = Double.Parse(suminfo[6].ToString()).ToString("##.000");
                    if (DBUtil.existedDemeritData(list[i].ToString()))
                    {
                        strTmp += "\n(" + Double.Parse(DBUtil.getDemeritInfo(list[i].ToString())[1].ToString()).ToString("#0.000") + ")";
                    }
                    string sGrade = "";
                    if (i < su)
                    {
                        sGrade = "수";
                    }
                    else if (i >= su && i < su + wo)
                    {
                        sGrade = "우";
                    }
                    else if (i >= su + wo && i < su + wo + mi + ya)
                    {
                        sGrade = "미";
                    }

                    strTmp += "\n" + "(" + sGrade + ")";

                    range.set_Value(Missing.Value, strTmp);

                    //순위
                    range = Util.OSheet.get_Range("M" + rowIndex.ToString(), Missing.Value);
                    double d = Double.Parse(suminfo[7].ToString());
                    string sRank = d.ToString() + " / " + DBUtil.getMTargetCount(getTargetType());

                    range.set_Value(Missing.Value, sRank);

                    rowIndex += 3;

                    if (progressBar.Value <= 50)
                    {
                        progressBar.Value += 1;
                    }
                    lblStateMsg.Text += ".";
                }
                progressBar.Value = 50;
                lblStateMsg.Text = "서식 적용 중...";
                range = Util.OSheet.get_Range("A13", "O" + (rowIndex - 1).ToString());
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
                range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;

                progressBar.Value = 70;
                lblStateMsg.Text = "내보내는 중....";
                
                range = Util.OSheet.get_Range("A" + rowIndex.ToString(), "O1000");
                range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                fileName = path + "\\다면평가및근무성적합산표(" + DBUtil.getOrganName(Config.Mvi.Organ) + ")_" + tscTargetType.Items[tscTargetType.SelectedIndex] + ".xls";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                progressBar.Value = 80;
                Util.OWorkBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Util.closeXls();
                progressBar.Value = 100;
                lblStateMsg.Text = "";
                
                
                lblStateMsg.Text = "근무성적평정결과표 파일 작성 중...";
                /*****************************************
                 * 근무성적평정결과표
                 *****************************************/
                progressBar.Value = 0;
                Util.openXls(Application.StartupPath + "\\EvalueResult");

                progressBar.Value = 15;
                //교명
                range = Util.OSheet.get_Range("M3", Missing.Value);
                range.set_Value(Missing.Value, DBUtil.getOrganName(Config.Mvi.Organ));

                //수 통계
                double[,] su_std = new double[6, 2] { { 100, 101 }, { 99, 100 }, { 98, 99 }, { 97, 98 }, { 96, 97 }, { 95, 96 } };
                int[,] su_arr = new int[6, 3];
                for (int i = 0; i < 6; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (j == 2)
                        {
                            su_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), su_std[i, 0], su_std[i, 1]);
                        }
                        else
                        {
                            su_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), j.ToString(), su_std[i, 0], su_std[i, 1]);
                        }
                    }
                }
                range = Util.OSheet.get_Range("C6", "E11");
                range.set_Value(Missing.Value, su_arr);

                progressBar.Value = 30;

                //우 통계
                double[,] wo_std = new double[5, 2] { { 94, 95 }, { 93, 94 }, { 92, 93 }, { 91, 92 }, { 90, 91 } };
                int[,] wo_arr = new int[5, 3];
                for (int i = 0; i < 5; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (j == 2)
                        {
                            wo_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), wo_std[i, 0], wo_std[i, 1]);
                        }
                        else
                        {
                            wo_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), j.ToString(), wo_std[i, 0], wo_std[i, 1]);
                        }
                    }
                }
                range = Util.OSheet.get_Range("C15", "E19");
                range.set_Value(Missing.Value, wo_arr);

                progressBar.Value = 45;

                //미 통계
                double[,] mi_std = new double[5, 2] { { 89, 90 }, { 88, 89 }, { 87, 88 }, { 86, 87 }, { 85, 86 } };
                int[,] mi_arr = new int[5, 3];
                for (int i = 0; i < 5; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (j == 2)
                        {
                            mi_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), mi_std[i, 0], mi_std[i, 1]);
                        }
                        else
                        {
                            mi_arr[i, j] = DBUtil.getStatisicsTotal(getTargetType(), j.ToString(), mi_std[i, 0], mi_std[i, 1]);
                        }
                    }
                }
                range = Util.OSheet.get_Range("C23", "E27");
                range.set_Value(Missing.Value, mi_arr);

                progressBar.Value = 60;

                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                fileName = path + "\\근무성적평정결과표(" + DBUtil.getOrganName(Config.Mvi.Organ) + ").xls";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                progressBar.Value = 75;
                Util.OWorkBook.SaveAs(fileName, Missing.Value, Missing.Value , Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                Util.closeXls();

                progressBar.Value = 100;

                lblStateMsg.Text = "근무성적평정총괄표 파일 작성 중...";

                /*****************************************
                 * 근무성적평정총괄표
                 *****************************************/

                progressBar.Value = 0;
                Util.openXls(Application.StartupPath + "\\EvalueTotal");

                progressBar.Value = 20;
                //교명
                range = Util.OSheet.get_Range("I3", Missing.Value);
                range.set_Value(Missing.Value, DBUtil.getOrganName(Config.Mvi.Organ));

                //평정대상자 인원 수 확인
                int iTargets = DBUtil.getMTargetCount(getTargetType());
                //int NumCount = 0;

                lblStateMsg.Text = "1면 작성 중...";

                /***************
                 * 1면
                 ***************/

                ArrayList target_list = DBUtil.getMTargetFromWorkEvalueSum(getTargetType());

                object[,] page1 = new object[25,6];
                for (int i = 0; i < 25; i++)
                {
                    if (iTargets <= i) break;

                    page1[i,0] = (i + 1).ToString();
                    ArrayList info = DBUtil.getMTargetInfo(target_list[i].ToString());
                    page1[i, 1] = info[0];
                    page1[i, 2] = info[1];
                    page1[i, 3] = info[2];
                    double d = DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString());
                    page1[i, 4] = d;
                    page1[i, 5] = DBUtil.getGradeName(DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString()));

                }

                range = Util.OSheet.get_Range("A7", "F31");
                range.set_Value(Missing.Value, page1);
                progressBar.Value = 30;
                lblStateMsg.Text = "2면 작성 중...";

                /***************
                * 2면
                ***************/

                object[,] page2 = new object[25, 6];
                for (int i = 25; i < 50; i++)
                {
                    if (iTargets <= i) break;

                    page2[i - 25, 0] = (i + 1).ToString();
                    ArrayList info = DBUtil.getMTargetInfo(target_list[i].ToString());
                    page2[i - 25, 1] = info[0];
                    page2[i - 25, 2] = info[1];
                    page2[i - 25, 3] = info[2];
                    double d = DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString());
                    page2[i - 25, 4] = d;
                    page2[i - 25, 5] = DBUtil.getGradeName(DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString()));

                }

                range = Util.OSheet.get_Range("H7", "M31");
                range.set_Value(Missing.Value, page2);

                if (iTargets <= 50)
                {
                    range = Util.OSheet.get_Range("A32", "N81");
                    range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
                }
                progressBar.Value = 50;
                lblStateMsg.Text = "3면 작성 중...";
                /***************
                * 3면
                ***************/

                object[,] page3 = new object[25, 6];
                for (int i = 50; i < 75; i++)
                {
                    if (iTargets <= i) break;

                    page3[i - 50, 0] = (i + 1).ToString();
                    ArrayList info = DBUtil.getMTargetInfo(target_list[i].ToString());
                    page3[i - 50, 1] = info[0];
                    page3[i - 50, 2] = info[1];
                    page3[i - 50, 3] = info[2];
                    double d = DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString());
                    page3[i - 50, 4] = d;
                    page3[i - 50, 5] = DBUtil.getGradeName(DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString()));

                }

                range = Util.OSheet.get_Range("A32", "F56");
                range.set_Value(Missing.Value, page3);

                progressBar.Value = 45;
                lblStateMsg.Text = "4면 작성 중...";
                /***************
                * 4면
                ***************/

                object[,] page4 = new object[25, 6];
                for (int i = 75; i < 100; i++)
                {
                    if (iTargets <= i) break;

                    page4[i - 75, 0] = (i + 1).ToString();
                    ArrayList info = DBUtil.getMTargetInfo(target_list[i].ToString());
                    page4[i - 75, 1] = info[0];
                    page4[i - 75, 2] = info[1];
                    page4[i - 75, 3] = info[2];
                    double d = DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString());
                    page4[i - 75, 4] = d;
                    page4[i - 75, 5] = DBUtil.getGradeName(DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString()));

                }

                range = Util.OSheet.get_Range("H32", "M56");
                range.set_Value(Missing.Value, page4);

                if (iTargets <= 100)
                {
                    range = Util.OSheet.get_Range("A57", "N81");
                    range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
                }

                progressBar.Value = 60;
                lblStateMsg.Text = "5면 작성 중...";
                /***************
               * 5면
               ***************/

                object[,] page5 = new object[25, 6];
                for (int i = 100; i < 125; i++)
                {
                    if (iTargets <= i) break;

                    page5[i - 100, 0] = (i + 1).ToString();
                    ArrayList info = DBUtil.getMTargetInfo(target_list[i].ToString());
                    page5[i - 100, 1] = info[0];
                    page5[i - 100, 2] = info[1];
                    page5[i - 100, 3] = info[2];
                    double d = DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString());
                    page5[i - 100, 4] = d;
                    page5[i - 100, 5] = DBUtil.getGradeName(DBUtil.getControlPointFromWorkControlTable(target_list[i].ToString()));

                }

                range = Util.OSheet.get_Range("A57", "F81");
                range.set_Value(Missing.Value, page5);

                progressBar.Value = 80;
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                fileName = path + "\\근무성적평정총괄표(" + DBUtil.getOrganName(Config.Mvi.Organ) + ").xls";
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                Util.OWorkBook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                lblStateMsg.Text = "";

                Util.closeXls();
                progressBar.Value = 100;
                progressBar.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류");
                Util.closeXls();
                progressBar.Value = 0;
                lblStateMsg.Text = "";
                progressBar.Visible = false;
            }
        }

        private void mnuDemeritList_Click(object sender, EventArgs e)
        {
            FormDemeritList f = new FormDemeritList();
            f.MdiParent = this;
            f.Show();
        }

        private void mnuACard_Click(object sender, EventArgs e)
        {
            FormACard f = new FormACard();
            f.MdiParent = this;
            f.Show();

            mnuACard.Enabled = false;
        }

        private void lnkRefresh_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            stateRefresh();
        }

        private void lnkVersionCheck_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MessageBox.Show("업데이트 프로그램 실행을 위해 현재 프로그램을 종료합니다.    \n\n업데이트를 진행하시겠습니까?  ", "확인", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                this.Close();
                Process.Start("InsaUpdateClient.exe", "CheckMode");
            }
        }

        private byte getTargetType()
        {
            return (byte)tscTargetType.SelectedIndex;
        }


        /* ***************
         * @요약 정보 dgvInfo 초기화
         * ***************/
        private void initDgvInfo()
        {            

            dgvInfo.Rows.Add(11);

            dgvInfo.Rows[0].Cells[0].Value = "확인자";
            dgvInfo.Rows[1].Cells[0].Value = "평정자";
            dgvInfo.Rows[2].Cells[0].Value = "설명";
            dgvInfo.Rows[3].Cells[0].Value = "전체 대상자";
            dgvInfo.Rows[4].Cells[0].Value = "일반";
            dgvInfo.Rows[5].Cells[0].Value = "보건";
            dgvInfo.Rows[6].Cells[0].Value = "전문상담";
            dgvInfo.Rows[7].Cells[0].Value = "사서";
            dgvInfo.Rows[8].Cells[0].Value = "영양";
            dgvInfo.Rows[9].Cells[0].Value = "기간제";            
            
        }

        private void mnuInfoVisible_Click(object sender, EventArgs e)
        {
            panInfo.Visible = !mnuInfoVisible.Checked;
            mnuInfoVisible.Checked = !mnuInfoVisible.Checked;
        }

        private void mnuEvalueInput_Click(object sender, EventArgs e)
        {
            frmCareerInput f = new frmCareerInput();
            f.MdiParent = this;
            f.Show();
        }
                

    }
}
